<!DOCTYPE html>
<html>
  <head>
      <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta content="yes" name="apple-mobile-web-app-capable" />
  <meta content="black" name="apple-mobile-web-app-status-bar-style" />
  <meta name="referrer" content="never">
  <meta name="keywords" content="">
  <meta name="description" content="">
  <meta name="author" content="kveln">
  <title>Gitlab CI 集成 Kubernetes | John Wong&#39;s Blog</title>
  <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
  <!-- <link href="https://blog.jwangkun.com/media/css/bootstrap.min.css" rel="stylesheet"> -->
  <!--  <link href="https://blog.jwangkun.com/media/css/all.min.css" rel="stylesheet" type="text/css"> -->
  <link href="https://cdn.bootcss.com/font-awesome/5.11.2/css/all.min.css" rel="stylesheet">
  <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
  <link rel="alternate" type="application/rss+xml" title="Gitlab CI 集成 Kubernetes | John Wong&#39;s Blog » Feed" href="https://blog.jwangkun.com/atom.xml">
  <link rel="stylesheet"href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.15.10/build/styles/androidstudio.min.css">
  <link href="https://blog.jwangkun.com/styles/main.css" rel="stylesheet">
  <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.15.10/build/highlight.min.js"></script>
  <!-- <script src="https://blog.jwangkun.com/media/scripts/jquery.min.js"></script> -->
  <script>hljs.initHighlightingOnLoad();</script>
  

    <meta property="og:description" content="Gitlab CI 集成 Kubernetes"/>
    <meta property="og:url" content="https://blog.jwangkun.com/post/uEZxv8lam/"/>
    <meta property="og:locale" content="zh-CN"/>
    <meta property="og:type" content="website"/>
    <meta property="og:site_name" content="John Wong&#39;s Blog"/>
  </head>
  <body>
  	<!-- Navigation -->
  <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
    <div class="container">
      <a class="navbar-brand" href="https://blog.jwangkun.com">John Wong&#39;s Blog</a>
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        Menu
        <i class="fas fa-bars"></i>
      </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          
          <li class="nav-item">
              
              <a class="nav-link" href="/">首页</a>
              
          </li>
          
          <li class="nav-item">
              
              <a class="nav-link" href="/archives">归档</a>
              
          </li>
          
          <li class="nav-item">
              
              <a class="nav-link" href="/tags">标签</a>
              
          </li>
          
          <li class="nav-item">
              
              <a class="nav-link" href="/post/about">关于</a>
              
          </li>
          
        </ul>
      </div>
    </div>
  </nav>
  <!-- Page Header -->
  <header class="masthead" style="background-image: url('https://blog.jwangkun.com/media/images/home-bg.jpg')">
    <div class="overlay"></div>
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
          <div class="post-heading">
          	<span class="tags">
          	 
            <a href="https://blog.jwangkun.com/tag/N_Jw3f6uk/" class="tag">Gitlab CI</a>
            
            <a href="https://blog.jwangkun.com/tag/B5IR6REH-N/" class="tag">Gitlab</a>
            
            <a href="https://blog.jwangkun.com/tag/efVGHoi38/" class="tag">Kubernetes</a>
            
        </span>
            <h1>Gitlab CI 集成 Kubernetes</h1>
            <span class="meta">
            	Posted on
              2020-10-15，17 min read
            </span>
          </div>
        </div>
      </div>
    </div>
  </header>

  <!-- Post Content -->
  <article>
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
          <h3 id="基本配置">基本配置</h3>
<p>首先将本节所用到的代码库从 Github 上获得：<a href="https://github.com/cnych/gitlab-ci-k8s-demo">cnych/gitlab-ci-k8s-demo</a>，可以在 Gitlab 上新建一个项目导入该仓库，当然也可以新建一个空白的仓库，然后将 Github 上面的项目 Clone 到本地后，更改远程仓库地址即可：</p>
<!-- more -->
<pre><code class="language-shell">$ git clone https://github.com/cnych/gitlab-ci-k8s-demo.git
$ cd gitlab-ci-k8s-demo
# Change the remote of the repository
$ git remote set-url origin ssh://git@git.qikqiak.com:30022/root/gitlab-ci-k8s-demo.git
# Now to push/&quot;import&quot; the repository run:
$ git push -u origin master
</code></pre>
<p>当我们把仓库推送到 Gitlab 以后，应该可以看到 Gitlab CI 开始执行构建任务了:<img src="https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/FLHIAa.jpg" alt="gitlab ci" loading="lazy"></p>
<p>此时 Runner Pod 所在的 namespace 下面也会出现两个新的 Pod：</p>
<pre><code class="language-shell">$ kubectl get pods -n kube-ops
NAME                                           READY     STATUS              RESTARTS   AGE
gitlab-7bff969fbc-k5zl4                        1/1       Running             0          4d
gitlab-ci-runner-0                             1/1       Running             0          4m
gitlab-ci-runner-1                             1/1       Running             0          4m
runner-9rixsyft-project-2-concurrent-06g5w4    0/2       ContainerCreating   0          4m
runner-9rixsyft-project-2-concurrent-1t74t9    0/2       ContainerCreating   0          4m
......
</code></pre>
<p>这两个新的 Pod 就是用来执行具体的 Job 任务的，这里同时出现两个证明第一步是并行执行的两个任务，从上面的 Pipeline 中也可以看到是 test 和 test2 这两个 Job。我们可以看到在执行 image_build 任务的时候出现了错误：</p>
<p><img src="https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/FPwuTu.jpg" alt="pipeline" loading="lazy">pipeline</p>
<p>我们可以点击查看这个 Job 失败详细信息：</p>
<pre><code class="language-shell">$ docker login -u &quot;${CI_REGISTRY_USER}&quot; -p &quot;${CI_REGISTRY_PASSWORD}&quot; &quot;${CI_REGISTRY}&quot;
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password
ERROR: Job failed: command terminated with exit code 1
</code></pre>
<p>出现上面的错误是因为我们并没有在 Gitlab 中开启 Container Registry，所以环境变量中并没有这些值，还记得前面章节中我们安装的 <a href="https://www.qikqiak.com/tags/harbor/">Harbor</a>吗？我们这里使用 <a href="https://www.qikqiak.com/tags/harbor/">Harbor</a> 来作为我们的镜像仓库，这里我们只需要把 <a href="https://www.qikqiak.com/tags/harbor/">Harbor</a> 相关的配置以参数的形式配置到环境中就可以了。定位到项目 -&gt; 设置 -&gt; CI/CD，展开<code>Environment variables</code>栏目，配置镜像仓库相关的参数值：</p>
<p><img src="https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/NWlfR4.jpg" alt="gitlab ci env" loading="lazy">gitlab ci env</p>
<p>配置上后，我们在上面失败的 Job 任务上点击“重试”，在重试过后依然可以看到会出现下面的错误信息：</p>
<pre><code class="language-shell">$ docker login -u &quot;${CI_REGISTRY_USER}&quot; -p &quot;${CI_REGISTRY_PASSWORD}&quot; &quot;${CI_REGISTRY}&quot;
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://registry.qikqiak.com/v2/: x509: certificate signed by unknown authority
ERROR: Job failed: command terminated with exit code 1
</code></pre>
<p>从错误信息可以看出这是因为登录私有镜像仓库的时候证书验证错误，因为我们根本就没有提供任何证书，所以肯定会失败的，还记得我们之前在介绍 Harbor 的时候的解决方法吗？第一种是在 Docker 的启动参数中添加上<code>insecure-registries</code>，另外一种是在目录<code>/etc/docker/certs.d/</code>下面添加上私有仓库的 CA 证书，同样，我们只需要在 dind 中添加 insecure 的参数即可：</p>
<pre><code class="language-yaml">services:
- name: docker:dind
  command: [&quot;--insecure-registry=registry.qikqiak.com&quot;]
</code></pre>
<blockquote>
<p>其中<code>registry.qikqiak.com</code>就是我们之前配置的私有镜像仓库地址。</p>
</blockquote>
<p>然后保存<code>.gitlab-ci.yml</code>文件，重新提交到代码仓库，可以看到又触发了正常的流水线构建了，在最后的阶段<code>deploy_review</code>仍然可以看到失败了，这是因为在最后的部署阶段我们使用<code>kubectl</code>工具操作集群的时候并没有关联上任何集群。</p>
<p>我们在 Gitlab CI 中部署阶段使用到的镜像是<code>cnych/kubectl</code>，该镜像的<code>Dockerfile</code>文件可以在仓库 <a href="https://github.com/cnych/docker-kubectl">cnych/docker-kubectl</a> 中获取：</p>
<pre><code class="language-yaml">FROM alpine:3.8

MAINTAINER cnych &lt;icnych@gmail.com&gt;

ENV KUBE_LATEST_VERSION=&quot;v1.13.4&quot;

RUN apk add --update ca-certificates \
 &amp;&amp; apk add --update -t deps curl \
 &amp;&amp; apk add --update gettext \
 &amp;&amp; apk add --update git \
 &amp;&amp; curl -L https://storage.googleapis.com/kubernetes-release/release/${KUBE_LATEST_VERSION}/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl \
 &amp;&amp; chmod +x /usr/local/bin/kubectl \
 &amp;&amp; apk del --purge deps \
 &amp;&amp; rm /var/cache/apk/*

 ENTRYPOINT [&quot;kubectl&quot;]
 CMD [&quot;--help&quot;]
</code></pre>
<p>我们知道<code>kubectl</code>在使用的时候默认会读取当前用户目录下面的<code>~/.kube/config</code>文件来链接集群，当然我们可以把连接集群的信息直接内置到上面的这个镜像中去，这样就可以直接操作集群了，但是也有一个不好的地方就是不方便操作，假如要切换一个集群还得重新制作一个镜像。所以一般我们这里直接在 Gitlab 上配置集成 Kubernetes 集群。</p>
<p>在项目页面点击<code>Add Kubernetes Cluster</code> -&gt; <code>Add existing cluster</code>：</p>
<p>1.Kubernetes cluster name 可以随便填</p>
<p>2.API URL 是你的集群的<code>apiserver</code>的地址， 一般可以通过输入<code>kubectl cluster-info</code>获取，Kubernetes master 地址就是需要的</p>
<pre><code class="language-shell">$ kubectl cluster-info
Kubernetes master is running at https://10.151.30.11:6443
KubeDNS is running at https://10.151.30.11:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
</code></pre>
<p>3.CA证书、Token、项目命名空间</p>
<p>对于我们这个项目准备部署在一个名为<code>gitlab</code>的 namespace 下面，所以首先我们需要到目标集群中创建一个 namespace:</p>
<pre><code class="language-shell">$ kubectl create ns gitlab
</code></pre>
<p>由于我们在部署阶段需要去创建、删除一些资源对象，所以我们也需要对象的 RBAC 权限，这里为了简单，我们直接新建一个 ServiceAccount，绑定上一个<code>cluster-admin</code>的权限：(gitlab-sa.yaml)</p>
<pre><code class="language-yaml">---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: gitlab
  namespace: gitlab

---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: gitlab
  namespace: gitlab
subjects:
  - kind: ServiceAccount
    name: gitlab
    namespace: gitlab
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
</code></pre>
<p>然后创建上面的 ServiceAccount 对象：</p>
<pre><code class="language-shell">$ kubectl apply -f sa.yaml
serviceaccount &quot;gitlab&quot; created
clusterrolebinding.rbac.authorization.k8s.io &quot;gitlab&quot; created
</code></pre>
<p>可以通过上面创建的 ServiceAccount 获取 CA 证书和 Token：</p>
<pre><code class="language-shell">$ kubectl get serviceaccount gitlab -n gitlab -o json | jq -r '.secrets[0].name'
gitlab-token-f9zp7

# 然后根据上面的Secret找到CA证书
$ kubectl get secret gitlab-token-f9zp7 -n gitlab -o json | jq -r '.data[&quot;ca.crt&quot;]' | base64 -d
xxxxxCA证书内容xxxxx

# 当然要找到对应的 Token 也很简单
$ kubectl get secret gitlab-token-f9zp7  -n gitlab -o json | jq -r '.data.token' | base64 -d
xxxxxxtoken值xxxx
</code></pre>
<p>填写上面对应的值添加集群：</p>
<p><img src="https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/Xbc1i5.jpg" alt="add k8s cluster" loading="lazy">add k8s cluster</p>
<h3 id="gitlab-ciyml">.gitlab-ci.yml</h3>
<p>现在 Gitlab CI 的环境都准备好了，我们可以来看下用于描述 Gitlab CI 的<code>.gitlab-ci.yml</code>文件。</p>
<p>一个 Job 在<code>.gitlab-ci.yml</code>文件中一般如下定义：</p>
<pre><code class="language-yaml"># 运行golang测试用例
test:
  stage: test
  script:
    - go test ./...
</code></pre>
<p>上面这个 Job 会在 test 这个 Stage 阶段运行。</p>
<p>为了指定运行的 Stage 阶段，可以在<code>.gitlab-ci.yml</code>文件中放置任意一个简单的列表：</p>
<pre><code class="language-yaml"># 所有 Stage
stages:
  - test
  - build
  - release
  - deploy
</code></pre>
<p>你可以指定用于在全局或者每个作业上执行命令的镜像：</p>
<pre><code class="language-yaml"># 对于未指定镜像的作业，会使用下面的镜像
image: golang:1.10.3-stretch
# 或者对于特定的job使用指定的镜像
test:
  stage: test
  image: python:3
  script:
    - echo Something in the test step in a python:3 image
</code></pre>
<blockquote>
<p>对于<code>.gitlab-ci.yml</code>文件的的其他部分，请查看如下文档介绍：https://docs.gitlab.com/ce/ci/yaml/README.html。</p>
</blockquote>
<p>在我们当前的项目中定义了 4 个构建阶段：test、build、release、review、deploy，完整的<code>.gitlab-ci.yml</code>文件如下：</p>
<pre><code class="language-yaml">image:
  name: golang:1.10.3-stretch
  entrypoint: [&quot;/bin/sh&quot;, &quot;-c&quot;]

# 为了能够使用go get，需要将代码放在 $GOPATH 中，比如你的 gitlab 域名是 mydomain.com，你的代码仓库是 repos/projectname，默认的 GOPATH 是 /go，然后你就需要将你的代码放置到 GOPATH 下面，/go/src/mydomain.com/repos/projectname，用一个软链接指过来就可以了
before_script:
  - mkdir -p &quot;/go/src/git.qikqiak.com/${CI_PROJECT_NAMESPACE}&quot;
  - ln -sf &quot;${CI_PROJECT_DIR}&quot; &quot;/go/src/git.qikqiak.com/${CI_PROJECT_PATH}&quot;
  - cd &quot;/go/src/git.qikqiak.com/${CI_PROJECT_PATH}/&quot;

stages:
  - test
  - build
  - release
  - review
  - deploy

test:
  stage: test
  script:
    - make test

test2:
  stage: test
  script:
    - sleep 3
    - echo &quot;We did it! Something else runs in parallel!&quot;

compile:
  stage: build
  script:
    # 添加所有的依赖，或者使用 glide/govendor/...
    - make build
  artifacts:
    paths:
      - app

image_build:
  stage: release
  image: docker:latest
  variables:
    DOCKER_DRIVER: overlay
    DOCKER_HOST: tcp://localhost:2375
  services:
    - name: docker:17.03-dind
      command: [&quot;--insecure-registry=registry.qikqiak.com&quot;]
  script:
    - docker info
    - docker login -u &quot;${CI_REGISTRY_USER}&quot; -p &quot;${CI_REGISTRY_PASSWORD}&quot; registry.qikqiak.com
    - docker build -t &quot;${CI_REGISTRY_IMAGE}:latest&quot; .
    - docker tag &quot;${CI_REGISTRY_IMAGE}:latest&quot; &quot;${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_NAME}&quot;
    - test ! -z &quot;${CI_COMMIT_TAG}&quot; &amp;&amp; docker push &quot;${CI_REGISTRY_IMAGE}:latest&quot;
    - docker push &quot;${CI_REGISTRY_IMAGE}:${CI_COMMIT_REF_NAME}&quot;

deploy_review:
  image: cnych/kubectl
  stage: review
  only:
    - branches
  except:
    - tags
  environment:
    name: dev
    url: https://dev-gitlab-k8s-demo.qikqiak.com
    on_stop: stop_review
  script:
    - kubectl version
    - cd manifests/
    - sed -i &quot;s/__CI_ENVIRONMENT_SLUG__/${CI_ENVIRONMENT_SLUG}/&quot; deployment.yaml ingress.yaml service.yaml
    - sed -i &quot;s/__VERSION__/${CI_COMMIT_REF_NAME}/&quot; deployment.yaml ingress.yaml service.yaml
    - |
      if kubectl apply -f deployment.yaml | grep -q unchanged; then
          echo &quot;=&gt; Patching deployment to force image update.&quot;
          kubectl patch -f deployment.yaml -p &quot;{\&quot;spec\&quot;:{\&quot;template\&quot;:{\&quot;metadata\&quot;:{\&quot;annotations\&quot;:{\&quot;ci-last-updated\&quot;:\&quot;$(date +'%s')\&quot;}}}}}&quot;
      else
          echo &quot;=&gt; Deployment apply has changed the object, no need to force image update.&quot;
      fi
    - kubectl apply -f service.yaml || true
    - kubectl apply -f ingress.yaml
    - kubectl rollout status -f deployment.yaml
    - kubectl get all,ing -l ref=${CI_ENVIRONMENT_SLUG}

stop_review:
  image: cnych/kubectl
  stage: review
  variables:
    GIT_STRATEGY: none
  when: manual
  only:
    - branches
  except:
    - master
    - tags
  environment:
    name: dev
    action: stop
  script:
    - kubectl version
    - kubectl delete ing -l ref=${CI_ENVIRONMENT_SLUG}
    - kubectl delete all -l ref=${CI_ENVIRONMENT_SLUG}

deploy_live:
  image: cnych/kubectl
  stage: deploy
  environment:
    name: live
    url: https://live-gitlab-k8s-demo.qikqiak.com
  only:
    - tags
  when: manual
  script:
    - kubectl version
    - cd manifests/
    - sed -i &quot;s/__CI_ENVIRONMENT_SLUG__/${CI_ENVIRONMENT_SLUG}/&quot; deployment.yaml ingress.yaml service.yaml
    - sed -i &quot;s/__VERSION__/${CI_COMMIT_REF_NAME}/&quot; deployment.yaml ingress.yaml service.yaml
    - kubectl apply -f deployment.yaml
    - kubectl apply -f service.yaml
    - kubectl apply -f ingress.yaml
    - kubectl rollout status -f deployment.yaml
    - kubectl get all,ing -l ref=${CI_ENVIRONMENT_SLUG}
</code></pre>
<p>上面的<code>.gitlab-ci.yml</code>文件中还有一些特殊的属性，如限制运行的的<code>when</code>和<code>only</code>参数，例如<code>only: [&quot;tags&quot;]</code>表示只为创建的标签运行，更多的信息，我可以通过查看 Gitlab CI YAML 文件查看：https://docs.gitlab.com/ce/ci/yaml/README.html由于我们在<code>.gitlab-ci.yml</code>文件中将应用的镜像构建完成后推送到了我们的私有仓库，而 Kubernetes 资源清单文件中使用的私有镜像，所以我们需要配置一个<code>imagePullSecret</code>，否则在 Kubernetes 集群中是无法拉取我们的私有镜像的：(替换下面相关信息为自己的)</p>
<pre><code class="language-shell">$ kubectl create secret docker-registry myregistry --docker-server=registry.qikqiak.com --docker-username=xxxx --docker-password=xxxxxx --docker-email=xxxx -n gitlab
secret &quot;myregistry&quot; created
</code></pre>
<p>在下面的 Deployment 的资源清单文件中会使用到创建的<code>myregistry</code>。</p>
<p>接下来为应用创建 Kubernetes 资源清单文件，添加到代码仓库中。首先创建 Deployment 资源：（deployment.yaml）</p>
<pre><code class="language-yaml">---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: gitlab-k8s-demo-__CI_ENVIRONMENT_SLUG__
  namespace: gitlab
  labels:
    app: gitlab-k8s-demo
    ref: __CI_ENVIRONMENT_SLUG__
    track: stable
spec:
  replicas: 2
  selector:
    matchLabels:
      app: gitlab-k8s-demo
      ref: __CI_ENVIRONMENT_SLUG__
  template:
    metadata:
      labels:
        app: gitlab-k8s-demo
        ref: __CI_ENVIRONMENT_SLUG__
        track: stable
    spec:
      imagePullSecrets:
        - name: myregistry
      containers:
      - name: app
        image: registry.qikqiak.com/gitdemo/gitlab-k8s:__VERSION__
        imagePullPolicy: Always
        ports:
        - name: http-metrics
          protocol: TCP
          containerPort: 8000
        livenessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 3
          timeoutSeconds: 2
        readinessProbe:
          httpGet:
            path: /health
            port: 8000
          initialDelaySeconds: 3
          timeoutSeconds: 2
</code></pre>
<blockquote>
<p>注意用上面创建的 myregistry 替换 imagePullSecrets。</p>
</blockquote>
<p>这是一个基本的 Deployment 资源清单的描述，像<code>__CI_ENVIRONMENT_SLUG__</code>和<code>__VERSION__</code>这样的占位符用于区分不同的环境，<code>__CI_ENVIRONMENT_SLUG__</code>将由 dev 或 live（环境名称）和<code>__VERSION__</code>替换为镜像标签。</p>
<p>为了能够连接到部署的 Pod，还需要 Service。对应的 Service 资源清单如下（service.yaml）：</p>
<pre><code class="language-yaml">---
apiVersion: v1
kind: Service
metadata:
  name: gitlab-k8s-demo-__CI_ENVIRONMENT_SLUG__
  namespace: gitlab
  labels:
    app: gitlab-k8s-demo
    ref: __CI_ENVIRONMENT_SLUG__
  annotations:
    prometheus.io/scrape: &quot;true&quot;
    prometheus.io/port: &quot;8000&quot;
    prometheus.io/scheme: &quot;http&quot;
    prometheus.io/path: &quot;/metrics&quot;
spec:
  type: ClusterIP
  ports:
    - name: http-metrics
      port: 8000
      protocol: TCP
  selector:
    app: gitlab-k8s-demo
    ref: __CI_ENVIRONMENT_SLUG__
</code></pre>
<p>我们的应用程序运行8000端口上，端口名为<code>http-metrics</code>，如果你还记得前面我们监控的课程中应该还记得我们使用<code>prometheus-operator</code>为 Prometheus 创建了<code>自动发现</code>的配置，所以我们在<code>annotations</code>里面配置上上面的这几个注释后，Prometheus 就可以自动获取我们应用的监控指标数据了。</p>
<p>现在 Service 创建成功了，但是外部用户还不能访问到我们的应用，当然我们可以把 Service 设置成 NodePort 类型，另外一个常见的方式当然就是使用 Ingress 了，我们可以通过 Ingress 来将应用暴露给外面用户使用，对应的资源清单文件如下：（ingress.yaml）</p>
<pre><code class="language-yaml">---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: gitlab-k8s-demo-__CI_ENVIRONMENT_SLUG__
  namespace: gitlab
  labels:
    app: gitlab-k8s-demo
    ref: __CI_ENVIRONMENT_SLUG__
  annotations:
    kubernetes.io/ingress.class: &quot;traefik&quot;
spec:
  rules:
  - host: __CI_ENVIRONMENT_SLUG__-gitlab-k8s-demo.qikqiak.com
    http:
      paths:
      - path: /
        backend:
          serviceName: gitlab-k8s-demo-__CI_ENVIRONMENT_SLUG__
          servicePort: 8000
</code></pre>
<blockquote>
<p>当然如果想配置 https 访问的话我们可以自己用 CA 证书创建一个 tls 密钥，也可以使用<code>cert-manager</code>来自动为我们的应用程序添加 https。</p>
</blockquote>
<p>当然要通过上面的域名进行访问，还需要进行 DNS 解析的，<code>__CI_ENVIRONMENT_SLUG__-gitlab-k8s-demo.qikqiak.com</code>其中<code>__CI_ENVIRONMENT_SLUG__</code>值为 live 或 dev，所以需要创建<code>dev-gitlab-k8s-demo.qikqiak.com</code> 和 <code>live-gitlab-k8s-demo.qikqiak.com</code> 两个域名的解析。</p>
<blockquote>
<p>我们可以使用 DNS 解析服务商的 API 来自动创建域名解析，也可以使用 <a href="https://github.com/kubernetes-incubator">Kubernetes incubator</a> 孵化的项目 <a href="https://github.com/kubernetes-incubator/external-dns">external-dns operator</a> 来进行操作。</p>
</blockquote>
<p>所需要的资源清单和<code>.gitlab-ci.yml</code>文件已经准备好了，我们可以小小的添加一个文件去触发下 Gitlab CI 构建：</p>
<pre><code class="language-shell">$ touch test1
$ git add .
$ git commit -m&quot;Testing the GitLab CI functionality #1&quot;
$ git push origin master
</code></pre>
<p>现在回到 Gitlab 中可以看到我们的项目触发了一个新的 Pipeline 的构建：</p>
<p><img src="https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/M5aDxg.jpg" alt="gitlab pipeline" loading="lazy">gitlab pipeline</p>
<p>可以查看最后一个阶段（stage）是否正确，如果通过了，证明我们已经成功将应用程序部署到 Kubernetes 集群中了，一个成功的<code>review</code>阶段如下所示：</p>
<p><img src="https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/GZezTs.jpg" alt="review success" loading="lazy">review success</p>
<p>整个 Pipeline 构建成功后，我们可以在项目的环境菜单下面看到多了一个环境：</p>
<p><img src="https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/PTl4AS.jpg" alt="env" loading="lazy">env</p>
<p>如果我们点击<code>终止</code>，就会调用<code>.gitlab-ci.yml</code>中定义的钩子<code>on_stop: stop_review</code>，点击<code>View deployment</code>就可以看到这次我们的部署结果（前提是DNS解析已经完成）：</p>
<p><img src="https://bxdc-static.oss-cn-beijing.aliyuncs.com/images/OfDR1j.jpg" alt="view deployment" loading="lazy">view deployment</p>
<p>这就是关于 Gitlab CI 结合 Kubernetes 进行 CI/CD 的过程，具体详细的构建任务还需要结合我们自己的应用实际情况而定。下节课给大家介绍使用 Jenkins + Gitlab + Harbor + Helm + Kubernetes 来实现一个完整的 CI/CD 流水线作业。</p>
<p>参考链接：https://edenmal.moe/post/2017/Kubernetes-WYNTK-GitLab-CI-Kubernetes-Presentation/</p>

          
          <p class="next-post">下一篇：
            <a href="https://blog.jwangkun.com/post/pyEGDeM0P/">
              <span class="post-title">
                基于 Jenkins、Gitlab、Harbor、Helm 和 Kubernetes 的 CI/CD&rarr;
              </span>
            </a>
          </p>
        
        <div class="comment">
          
        </div>
      </div>
    </div>
  </article>
 <!-- Footer -->
  <footer>
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">
          <ul class="list-inline text-center">
            
            
              
            
              
            
              
            
              
            
              
            
              
            
              
              <li class="list-inline-item">
              <a href="https://blog.jwangkun.com/atom.xml" target="_blank">
                <span class="fa-stack fa-lg">
                  <i class="fas fa-circle fa-stack-2x"></i>
                  <i class="fas fa-rss fa-stack-1x fa-inverse"></i>
                </span>
              </a>
              </li>
          </ul>
          <p class="copyright text-muted">Copyright &copy;<span>John Wong&#39;s Blog</span><br><a href="https://github.com/getgridea/gridea" class="Themeinfo">Powered by Gridea</a></p>
        </div>
      </div>
    </div>
   </footer>
  <!-- Bootstrap core JavaScript -->
  <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
  <!-- <script src="https://blog.jwangkun.com/media/scripts/bootstrap.bundle.min.js"></script> -->
  <!-- Bootstrap core JavaScript -->
  <script src="https://cdn.jsdelivr.net/gh/Alanrk/clean-cdn@1.0/scripts/clean-blog.min.js"></script>
  <!-- <script src="https://blog.jwangkun.com/media/scripts/clean-blog.min.js"></script> -->
  <script src="//instant.page/3.0.0" type="module" defer integrity="sha384-OeDn4XE77tdHo8pGtE1apMPmAipjoxUQ++eeJa6EtJCfHlvijigWiJpD7VDPWXV1"></script>
  <style type="text/css">a.back_to_top{text-decoration:none;position:fixed;bottom:40px;right:30px;background:#f0f0f0;height:40px;width:40px;border-radius:50%;line-height:36px;font-size:18px;text-align:center;transition-duration:.5s;transition-propety:background-color;display:none}a.back_to_top span{color:#888}a.back_to_top:hover{cursor:pointer;background:#dfdfdf}a.back_to_top:hover span{color:#555}@media print,screen and(max-width:580px){.back_to_top{display:none!important}}</style>
<a id="back_to_top" href="#" class="back_to_top">
  <span>▲</span></a>
<script>$(document).ready((function(_this) {
    return function() {
      var bt;
      bt = $('#back_to_top');
      if ($(document).width() > 480) {
        $(window).scroll(function() {
          var st;
          st = $(window).scrollTop();
          if (st > 30) {
            return bt.css('display', 'block')
          } else {
            return bt.css('display', 'none')
          }
        });
        return bt.click(function() {
          $('body,html').animate({
            scrollTop: 0
          },
          800);
          return false
        })
      }
    }
  })(this));
  var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?84ab85460bfbe79dbe5776a1df139a8f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
  </script>
  
<script type="text/javascript" src="https://v1.cnzz.com/z_stat.php?id=1279350888&web_id=1279350888"></script>

  </body>
</html>

